package com.ruoyi.framework.pool;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.ruoyi.system.domain.THost;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.KeyedPooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;

/**
 * @description: 连接工厂
 * @author: stone
 * @date: Created by 2022/4/16 23:29
 * @version: 1.0.0
 * @pakeage: com.ruoyi.framework.pool
 */
@Slf4j
public class SshConnectFactory implements KeyedPooledObjectFactory<THost, Session> {
    @Override
    public PooledObject<Session> makeObject(THost host) throws Exception {
        log.info("创建对象 =====> {}", host);

        JSch jSch = new JSch();
        Session session = jSch.getSession(host.getUsername(), host.getHostname(), host.getPort());
        session.setPassword(host.getPasswd());
        session.setTimeout(60 * 60 * 12);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(60000);
        return new DefaultPooledObject<>(session);
    }

    @Override
    public void destroyObject(THost host, PooledObject<Session> pooledObject) throws Exception {
        log.info("销毁对象 ===> {}", host);
        Session session = pooledObject.getObject();
        session.disconnect();
    }

    @Override
    public boolean validateObject(THost host, PooledObject<Session> pooledObject) {
        log.info("验证对象是否可用 ===> {}", host);
        Session session = pooledObject.getObject();
        if (session.isConnected()) {
            try {
                session.sendKeepAliveMsg();
                return true;
            } catch (Exception e) {
                log.info("ssh连接池中session连接实例已失效...{} ，异常信息 ==> {}", host, e.getMessage());
                return false;
            }
        }
        return true;
    }

    @Override
    public void activateObject(THost host, PooledObject<Session> pooledObject) throws Exception {
        //激活对象
        Session session = pooledObject.getObject();
        log.info("激活对象 ===> {} ==> {}", host, session.getHost());

    }

    @Override
    public void passivateObject(THost host, PooledObject<Session> pooledObject) throws Exception {
        Session session = pooledObject.getObject();
        log.info("归还对象 ===> {} ==> {}", host, session);
    }


}
